#!/usr/bin/env python
# encoding: utf-8
"""
core_definitions.py

Created by Niall Richard Murphy on 2012-03-15.
"""

import re
import sys

def UsingSafeSSHVersion(self, router):
  """The only safe SSH version is 2; if 1, or no SSH, return this."""
  if router.ssh_server is None:
    return dict(router=router.describe(), ssh_version=None)
  elif router.ssh_server is 1:
    return dict(router=router.describe(), ssh_version=1)
  else:
    return True

def HasConsolePassword(self, router):
  """Does the router have a console password?"""
  if router.console_password is None:
    return None
  else:
    return True
  
def HasSecureTransportForVTYs(self, router):
  """Our devices may have ways other than telnet of getting to them;
  enumerate these ways."""
  for vty_entry in router.vty_configs:
    props = router.get_vty_config(vty_entry)
    inputs = props.get('inputm', "")
    if 'telnet' in inputs and 'ssh' in inputs:
      return dict(router=router.describe(), transport_includes='telnet')
    elif 'telnet' in inputs:
      return dict(router=router.describe(), transport_only='telnet')

def HasUnreferencedACL(self, router):
  """Find the first unreferenced ACL (currently defined as unused
  by vty access groups or interface access groups.) This naive
  implementation will only find the first one.

  Router:
    A virtual router object.

  Returns:
    Dictionary mapping between router name and missing ACL."""
  for aclid in router.iterate_aclids():
    if aclid not in (router.vty_used_access_groups() or
                     router.interface_used_access_groups()):
      return dict(router=router.describe(), acl=aclid)
  return True

def HasUnACLedVTYs(self, router):
  """Does a router have a VTY with no ACLs protecting it?

  Args:
    router: A virtual router object.

  Returns:
    True: if ACLs are protecting all VTYs.
    Dictionary: maps router names to VTYs missing an ACL."""
  for vt in router.iterate_all_vtys():
    v4_acl_name = vt.values()[0].get('acl', None)
    v6_acl_name = vt.values()[0].get('aclv6', None)
    if (v4_acl_name is None and v6_acl_name is None):
      return dict(router=router.describe(), vt_id=vt.keys()[0])
  return True


def HasDefinedLoopbackWithAddresses(self, router):
  """Does this router have a Loopback0 interface with defined addresses?"""
  l0 = router.interfaces.get('Loopback0', None)
  addr1 = l0.get('addr1', None)
  addr2 = l0.get('addr2', None)
  if l0 is None:
    return False
  elif l0 is not None and (addr1 is None and addr2 is None):
    return False
  else:
    return True

